<?php

namespace App\Http\Controllers\Admin\Goods;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Goods;
use App\Model\Gprice;
use App\Model\Sale_promotion;
use App\Http\Controllers\Common\CommonApi;
use App\Http\Controllers\CommonApi\CommonApi as CustomerPage;
use Illuminate\Support\Facades\Redis;
use App\Jobs\StartPromotion;
use App\Jobs\EndPromotion;
use Carbon\Carbon;
use App\Http\Controllers\Home\Index\Api\IndexApi;

class SalePromotionController extends Controller
{   
    /**
     * 显示商品促销管理列表的页面
     * @author wuboheng <[email address]>
     * @return [void]
     */
    public function list(Request $request)
    {
        $promotion = Sale_promotion::select(['id', 'gid', 'pid', 'gname', 'sale_price', 'sale_start_time', 'sale_end_time', 'sale_sort', 'ad_address', 'path', 'state'])
            ->orderBy('state', 'asc')
            ->get()
            ->toArray();

        foreach ($promotion as &$v) {
            $goods = Gprice::select('size', 'color')
                ->where('id', $v['pid'])
                ->first()
                ->toArray();

            $v['goods'] = $goods;
        }

        $promotion = CustomerPage::CustomPagination($request, $promotion, 10);

        return view('Admin/Goods/sale-promotion-list', ['promotion' => $promotion]);

        // dd($promotion);
    }


    /**
     * 显示商品促销添加的页面
     * @author wuboheng <[email address]>
     * @return [view] [description]
     */
    public function add(Request $request)
    {   
        //获取目前商品是否正在促销或者准备促销,如果是,则不允许再添加商品促销
        if ( $request->input('is_discount') == '0' || $request->input('is_discount') == '1') {
            return back()->with('errorMsg', '商品正在促销或者准备促销,无法再添加促销活动');
        }


        $pid = $request->input('pid');

        $goodsPrice = Gprice::select(['id', 'price', 'storage', 'size', 'color', 'sales', 'is_discount', 'state'])
            ->where('id', $pid)
            ->first()
            ->toArray();

        $goods = Gprice::find($pid)
            ->findGoods
            ->toArray();

        // dd($goods, $goodsPrice);

        return view('Admin/Goods/sale-promotion', [

            'goods' => $goods,
            'goodsprice' => $goodsPrice,

            ]);

    }


    /**
     * 执行商品促销添加
     * @author wuboheng <[email address]>
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function doAdd(Request $request)
    {   
        //获取当前时间(单位秒)
        $nowTime = time();

        //如果目前时间比促销开始时间要迟,则返回去
        if ( strtotime($request->input('sale_start_time'))  < $nowTime) {

            return back()->with('message', '促销开始时间必需大于现在时间');
        }

        //判断促销结束时间必需大于开始时间
        if ( strtotime($request->input('sale_start_time')) >= strtotime($request->input('sale_end_time')) ) {
            
            return back()->with('message', '促销结束时间必需大于开始时间');
        }

        //如果有设置广告位置,但又没有上传图片,则返回并提示
        if ( ( $request->input('ad_address') !== '0' ) &&  ( $request->file('file_upload') == '' ) ) {

            return back()->with('message', '若设置了广告位,则必须上传广告图');
        }

        //表单验证
        $this->validate($request, [
            'sale_price' => 'bail|required|numeric|min:0|max:9999999.99',
            'sale_start_time' => 'bail|required|',
            'sale_end_time' => 'bail|required|',
            'sale_sort' => 'bail|required|min:0|integer',
            'ad_address' => 'bail|required',
            // 'file_upload' => 'bail|required',
        ],
        [
            'sale_price.required' => '促销价必填',
            'sale_price.numeric' => '价格必需为数字',
            'sale_price.min' => '促销价应大于等于0',
            'sale_price.max' => '促销价最多为9999999.99',
            'sale_start_time.required' => '促销开始时间必填',
            'sale_end_time.required' => '促销结束时间必填',
            'sale_sort.required' => '排序必填',
            'sale_sort.min' => '排序最少为0',
            'sale_sort.integer' => '排序必需为整数',
            'ad_address.required' => '广告位置必选',
            // 'file_upload.required' => '广告图片必选',

        ]);

        // $date = $request->input('sale_start_time');
        // $path = $request->file('file_upload')->store('star');

        $path = '';
        //调用七牛云,执行图片上传
        if ($request->file('file_upload') !== null) {
            $common = new CommonApi;
            $res = $common->uploadToQiNiu($request, 'file_upload');

            if($res){

                    $pic = $res['data']['key'];
            }

            //获取成功上传到七牛云的路径
            $path = "http://owv3oi69q.bkt.clouddn.com/".$pic;
        }
        
        //执行添加促销
        $result = Sale_promotion::insertGetId([

            'gid' => $request->input('gid'),
            'pid' => $request->input('pid'),
            'sid' => $request->input('sid'),
            'gname' => $request->input('gname'),
            'sale_price' => $request->input('sale_price'),
            'sale_start_time' => strtotime($request->input('sale_start_time')),
            'sale_end_time' => strtotime($request->input('sale_end_time')),
            'sale_sort' => $request->input('sale_sort'),
            'ad_address' => $request->input('ad_address'),
            'path' => $path,
            'state' => 0,

        ]);

        

        //如果添加成功,把该商品在goods_price表的促销价格也一并修改
        if ($result) {

            //修改good_price表的is_discount字段为0(准备促销)
            Gprice::where('id', $request->input('pid'))
                ->update(['is_discount' => 0]);

            //===========  使用队列任务修改goods_price表的促销价格  ==============
            
            //先获取要修改的模型
            $salePromotion = Sale_promotion::find($result);
            $goodsPrice = Gprice::find($request->input('pid'));
            $indexApi = new IndexApi();

            //获取当前时间(单位秒)
            $nowTime = time();

            //获取促销开始的时间(单位秒)
            $executeTime = strtotime($request->input('sale_start_time'));
            
            //获取促销结束的时间(单位秒)
            $endTime = strtotime($request->input('sale_end_time'));

            $gapStart = $executeTime - $nowTime;     //从现在到促销开始的时间差(单位秒)
            $gapEnd = $endTime - $nowTime;     //从现在到促销结束的时间差(单位秒)

            // dd(date('Y-m-d H:i:s', $nowTime), $request->input('sale_start_time'), $nowTime, $carbon, $executeTime, Carbon::now()->addSecond(($executeTime - $nowTime)), $gapStart);
            
            //使用队列延后执行修改促销价格的任务
            StartPromotion::dispatch($salePromotion, $goodsPrice, $indexApi)->delay(Carbon::now()->addSeconds($gapStart));
            EndPromotion::dispatch($salePromotion, $goodsPrice, $indexApi)->delay(Carbon::now()->addSeconds($gapEnd));
            
            //队列像这样写也OK
            // $job = (new StartPromotion($salePromotion, $goodsPrice))->delay(Carbon::now()->addSecond($gapStart));
            // $this->dispatch($job);

            //====================================================================
            
            //把有关于Sale_promotion表的Redis都清除
            Redis::del('homePromotion');
            Redis::del('indexAsidePromotion');
            Redis::del('homeHotSale');

            //清除首页懒加载的Redis
            Redis::del('lazyLoad:0');
            Redis::del('lazyLoad:1');
            Redis::del('lazyLoad:2');
            Redis::del('lazyLoad:3');
            Redis::del('lazyLoad:4');
            Redis::del('lazyLoad:5');

            //删除此商品的哈希Redis
            Redis::hDel('hotData', 'hotData:'.$request->input('gid'));

            //跳链回去商品详情页
            return redirect('/Admin/goods/'.$request->input('gid'))->with('result1', '添加促销成功');    

        } else {

            //失败跳链回去商品详情页
            return redirect('/Admin/goods/'.$request->input('gid'))->with('result1', '添加促销失败'); 
        }

        // dd($path);
        
        // dd($date, strtotime($date));
    }

    /**
     * 显示编辑页面
     * @author wuboheng <[email address]>
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function edit(Request $request)
    {   
        //如果促销状态不是'准备促销',则不能再修改促销了
        if ( $request->input('state') !== '0' ) {
            return back()->with('errorMsg', '促销已经开始或结束,不能再修改');
        }


        $id = $request->input('id');
        // dd($id);
        $promotion = Sale_promotion::select(['id', 'gid', 'pid', 'gname', 'sale_price', 'sale_start_time', 'sale_end_time', 'sale_sort', 'ad_address', 'path'])
            ->where('id', $id)
            ->first()
            ->toArray();

        // dd($promotion);
        
        return view('Admin/Goods/sale-promotion-edit', ['promotion' => $promotion]);
    }

    /**
     * 执行修改
     * @return [type] [description]
     */
    public function doUpdate(Request $request)
    {   
        //判断是否有新的图片上传
        if ($request->file('file_upload') == null) {

            //如果没有新的图片,则用回原来的
            $path = $request->input('originalpic');

        } else {

            //调用七牛云,执行图片上传
            $common = new CommonApi;
            $res = $common->uploadToQiNiu($request, 'file_upload');

            if($res){

                    $pic = $res['data']['key'];
            }

            //获取成功上传到七牛云的路径
            $path = "http://owv3oi69q.bkt.clouddn.com/".$pic;

        }

        // dd($path);
        
        //获取当前时间(单位秒)
        $nowTime = time();

        //如果目前时间比促销开始时间要迟,则返回去
        if ( strtotime($request->input('sale_start_time'))  < $nowTime) {

            return back()->with('message', '促销开始时间必需大于现在时间');
        }

    
        //判断促销结束时间必需大于开始时间
        if ( strtotime($request->input('sale_start_time')) > strtotime($request->input('sale_end_time')) ) {
            // echo 123;
            return back()->with('message', '促销结束时间必需大于开始时间');
        }

        // dd($request->input('ad_address'));

        //如果有设置广告位置,但又没有上传图片,则提示
        if ( ( $request->input('ad_address') !== '0' ) && ( $request->file('file_upload') == null ) && ($request->input('originalpic') == '') ) {

            return back()->with('message', '若设置了广告位,则必须上传广告图');
        }

        //表单验证
        $this->validate($request, [
            'sale_price' => 'bail|required|numeric|min:0|max:9999999.99',
            'sale_start_time' => 'bail|required|',
            'sale_end_time' => 'bail|required|',
            'sale_sort' => 'bail|required|min:0|integer',
            'ad_address' => 'bail|required',
            
        ],
        [
            'sale_price.required' => '促销价必填',
            'sale_price.numeric' => '价格必需为数字',
            'sale_price.min' => '促销价应大于等于0',
            'sale_price.max' => '促销价最多为9999999.99',
            'sale_start_time.required' => '促销开始时间必填',
            'sale_end_time.required' => '促销结束时间必填',
            'sale_sort.required' => '排序必填',
            'sale_sort.min' => '排序最少为0',
            'sale_sort.integer' => '排序必需为整数',
            'ad_address.required' => '广告位置必选',
            

        ]);


        //执行修改
        $res = Sale_promotion::where('id', $request->input('id'))
            ->update([

                'sale_price' => $request->input('sale_price'),
                'sale_start_time' => strtotime($request->input('sale_start_time')),
                'sale_end_time' => strtotime($request->input('sale_end_time')),
                'sale_sort' => $request->input('sale_sort'),
                'ad_address' => $request->input('ad_address'),
                'path' => $path,

            ]);

        //判断并输出
        if ($res) {

            //修改过后,同样需要用队列任务去把本次的促销信息延时执行一次
            //===========  使用队列任务修改goods_price表的促销价格  ==============
            
            //先获取要修改的模型
            $salePromotion = Sale_promotion::find($request->input('id'));
            $goodsPrice = Gprice::find($request->input('pid'));
            $indexApi = new IndexApi();

            //获取当前时间(单位秒)
            $nowTime = time();

            //获取促销开始的时间(单位秒)
            $executeTime = strtotime($request->input('sale_start_time'));
            
            //获取促销结束的时间(单位秒)
            $endTime = strtotime($request->input('sale_end_time'));

            $gapStart = $executeTime - $nowTime;     //从现在到促销开始的时间差(单位秒)
            $gapEnd = $endTime - $nowTime;     //从现在到促销结束的时间差(单位秒)

            
            //使用队列延后执行修改促销价格的任务
            StartPromotion::dispatch($salePromotion, $goodsPrice, $indexApi)->delay(Carbon::now()->addSeconds($gapStart));
            EndPromotion::dispatch($salePromotion, $goodsPrice, $indexApi)->delay(Carbon::now()->addSeconds($gapEnd));
            

            //====================================================================

            //把有关于Sale_promotion表的Redis都清除
            Redis::del('homePromotion');
            Redis::del('indexAsidePromotion');
            Redis::del('homeHotSale');

            //删除此商品的哈希Redis
            Redis::hDel('hotData', 'hotData:'.$request->input('gid'));

            return redirect('Admin/salepromotion/list')->with('message', '修改成功');

        } else {

            return redirect('Admin/salepromotion/list')->with('message', '修改失败');
        }


    }

    /**
     * 设置促销为生效
     */
    public function setActive(Request $request)
    {
        $id = $request->input('id');

        $res = Sale_promotion::where('id', $id)
            ->update(['state' => 1]);

        if ($res) {

            //把有关于Sale_promotion表的Redis都清除
            Redis::del('homePromotion');
            Redis::del('indexAsidePromotion');
            Redis::del('homeHotSale');

            $data = [
                'code' => 200,
                'msg' => '设置生效成功',
            ];
        } else {
            $data = [
                'code' => 404,
                'msg' => '设置生效失败',
            ];
        }

        return response()->json($data);
    }


    /**
     * 设置促销为失效
     */
    public function setNotActive(Request $request,$id)
    {      
        //获取目前促销的状态,如果状态已经是2了,就不需要再让促销失效
        $state = $request->input('state');

        // echo $state; exit;

        //修改goods_price表
        $goods_price = Gprice::select(['goods_price.id as id', 'goods_price.price as price', 'discount_price', 'is_discount'])
            ->join('sale_promotion', 'sale_promotion.pid', '=', 'goods_price.id')
            ->where('sale_promotion.id', $id)
            ->first();

        $goods_price->discount_price = $goods_price->price;   //把促销价变回原价
        $goods_price->is_discount = 2;   //把状态变为2(没有促销)
        $goods_price->save();
        
        // echo '<pre>';
        // print_r($goods_price);
        // echo '</pre>';
        // exit;

        //修改sale_promotion表的状态为2(促销已失效或结束)
        $res = Sale_promotion::where('id', $id)
            ->update(['state' => 2]);

        if ($res) {

            //把有关于Sale_promotion表的Redis都清除
            Redis::del('homePromotion');
            Redis::del('indexAsidePromotion');
            Redis::del('homeHotSale');

            //删除此商品的哈希Redis
            Redis::hDel('hotData', 'hotData:'.$request->input('gid'));
     
            $data = [
                'code' => 200,
                'msg' => '设置过期成功',
            ];
        } else {
            $data = [
                'code' => 404,
                'msg' => '设置过期失败',
            ];
        }

        return response()->json($data);
    }

    




}
